#!/usr/bin/env python
#coding: utf-8

from twisted.enterprise import adbapi
from twisted.internet import defer
import time
import random

DB_DRIVER = "MySQLdb"

DB_ARGS = {
    'db': 'test',
    'user': 'root',
    'passwd': '123456',
    }

def _dbSucess(results):
    for resultinfo in results:
        sucess,result=resultinfo
        print result
    reactor.stop()

def _dbError(failure):
    print failure.getErrorMessage( )


if __name__ == "__main__":
    from twisted.internet import reactor
    dbConnection = adbapi.ConnectionPool(DB_DRIVER, **DB_ARGS)
    dl=[]
    for i in xrange(5):
        #dbConnection.runQuery('select * from test limit 1').addCallback(_dbSucess).addErrback(_dbError)
        #dbConnection.runQuery('insert into test (name) values ("%s")'%''.join(random.sample('ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789',20))).addCallback(_dbSucess).addErrback(_dbError)
        dl.append(dbConnection.runQuery('select * from test limit 5'))
    #reactor.callWhenRunning(reactor.stop)
    defer.DeferredList(dl,consumeErrors=True).addCallback(_dbSucess).addErrback(_dbError)

    print 'Running the reactor...'
    reactor.run()
    print 'Reactor stopped.'

